//
//  DataModel.swift
//  Checklists
//
//  Created by cygarm on 15/12/1.
//  Copyright © 2015年 Razeware. All rights reserved.
//

import Foundation

class DataModel {
	var lists = [Checklist]()
	var indexOfSelectedChecklist: Int {
		get {
			return NSUserDefaults.standardUserDefaults().integerForKey("ChecklistIndex")
		}
		set {
			NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: "ChecklistIndex")
		}
	}
	class func nextChecklistItemID() -> Int {
		let userDefaults = NSUserDefaults.standardUserDefaults()
		let itemID = userDefaults.integerForKey("ChecklistItemID")
		userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID")
		userDefaults.synchronize()
		
		return itemID
	}
	
	init() {
		loadChecklists()
		registerDefaults()
		handleFirstTime()
	}
	
	func registerDefaults() {
		/*
		NSUserDefault's integerForKey() method returns 0 if it cannot find the value for the key you specify
		*/
		let dictionary = ["ChecklistIndex": -1,
											"FirstTime": true, 
											"ChecklistItemID": 0]
		
		NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
	}
	
	func documentsDirectory() -> String {
		let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
		return paths[0]
	}
	
	func dataFilePath() -> String {
		return (documentsDirectory() as NSString).stringByAppendingPathComponent("Checklists.plist")
	}
	
	func saveChecklists() {
		let data = NSMutableData()
		let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
		archiver.encodeObject(lists, forKey: "Checklists")
		archiver.finishEncoding()
		data.writeToFile(dataFilePath(), atomically: true)
	}
	
	func loadChecklists() {
		let path = dataFilePath()
		if NSFileManager.defaultManager().fileExistsAtPath(path) {
			if let data = NSData(contentsOfFile: path) {
				let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
				lists = unarchiver.decodeObjectForKey("Checklists") as! [Checklist]
				unarchiver.finishDecoding()
				sortChecklists()
			}
		}
	}
	
	func sortChecklists() {
		lists.sortInPlace { (checklist1, checklist2) -> Bool in
			checklist1.name.localizedStandardCompare(checklist2.name) == NSComparisonResult.OrderedAscending
		}
	}
	
	func handleFirstTime() {
		let usrDefaults = NSUserDefaults.standardUserDefaults()
		let firstTime = usrDefaults.boolForKey("FirstTime")
		if firstTime {
			let checklist = Checklist(name: "List")
			lists.append(checklist)
			indexOfSelectedChecklist = 0
			usrDefaults.setBool(false, forKey: "FirstTime")
		}
	}
}
